import 'dart:async';
import 'dart:convert';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/ai_poster/ai_poster_index_response_bean.dart';
import 'package:e_reception_flutter/ui/ai_poster/ai_poster_index_view_model.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/click_back_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_mixin/navigator_page_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/mixin/vg_place_holder_status_mixin.dart';
import 'package:e_reception_flutter/vg_widgets/vg_pull_to_refresh_widget/vg_pull_to_refresh_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_pull_to_refresh_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'ai_poster_psd_list_bean.dart';
import 'edit_ai_poster_detail_page.dart';

/// ai海报首页
class AiPosterModelPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "AiPosterModelPage";

  @override
  AiPosterModelPageState createState() => AiPosterModelPageState();

}

class AiPosterModelPageState
    extends BasePagerState<AiPosterIndexListItemBean, AiPosterModelPage>
    with
        AutomaticKeepAliveClientMixin,
        VgPlaceHolderStatusMixin,
        NavigatorPageMixin {

  AiPosterIndexViewModel viewModel;
  StreamSubscription _aiPosterStreamSubscription;
  
  String _name;
  String _address;
  String _logo;

  ///获取state
  static AiPosterModelPageState of(BuildContext context) {
    final AiPosterModelPageState result =
    context.findAncestorStateOfType<AiPosterModelPageState>();
    return result;
  }


  @override
  void initState() {
    super.initState();
    viewModel = AiPosterIndexViewModel(this);
    viewModel?.refresh();
    _aiPosterStreamSubscription =
        VgEventBus.global.on<MonitoringAiPosterIndexClass>()?.listen((event) {
          viewModel?.refresh();
        });
  }

  @override
  void dispose() {
    _aiPosterStreamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      resizeToAvoidBottomInset: false,
      resizeToAvoidBottomPadding: false,
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: _toMainColumnWidget(),
    );
  }

  Widget _toMainColumnWidget() {
    return  MixinPlaceHolderStatusWidget(
        emptyOnClick: () => viewModel?.refresh(),
        errorOnClick: () => viewModel.refresh(),
        // child: child,
        child: VgPullRefreshWidget.bind(
            state: this, viewModel: viewModel, child: _toGridPage())
    );
  }


  Widget _toGridPage(){
    return GridView.builder(
      padding: EdgeInsets.only(
          left: 15,
          right: 15,
          top: 3,
          bottom: getNavHeightDistance(context)
      ),
      itemCount: data?.length ?? 0,
      physics: BouncingScrollPhysics(),
      shrinkWrap: true,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        mainAxisSpacing: 5,
        crossAxisSpacing: 5,
        childAspectRatio: 1 / 1.73,
      ),
      itemBuilder: (BuildContext context, int index) {
        return _toGridItemWidget(context,data?.elementAt(index));
      },
    );
  }


  Widget _toGridItemWidget(BuildContext context, AiPosterIndexListItemBean itemBean) {
    return ClickBackgroundWidget(
      behavior: HitTestBehavior.opaque,
      onTap: ()async{
        String url = getUrl();
        List response = json.decode(itemBean?.psdurl);
        List<AiPosterPsdListBean> multiColorList = List()..addAll(
            response.map((o) => AiPosterPsdListBean.fromMap(o))
        );
        String currentPsd;
        if(multiColorList != null && multiColorList.length > 0){
          // String psdJson = json.encode(_multiColorList[0].data);
          for(int i = 0; i < multiColorList.length; i++){
            List<PsdDateBean> data = multiColorList[i].data;
            for(int j = 0; j < data.length; j++){
              PsdDateBean psdData = data[j];
              if(psdData?.name?.contains("地址-") && StringUtils.isNotEmpty(_address)){
                psdData?.content = _address;
              }
              if(psdData?.name?.contains("名称-") && StringUtils.isNotEmpty(_name)){
                psdData?.content = _name;
              }
              if(psdData?.name?.contains("logo-") && StringUtils.isNotEmpty(_logo)){
                psdData?.content = _logo;
              }
              data[j] = psdData;
            }
            multiColorList[i].data = data;
            multiColorList[i].dataJson = json.encode(data);
          }
          String psdJson = multiColorList[0].dataJson;
          // String psdJson = json.encode(multiColorList[0].data);
          currentPsd = getPsd(psdJson);
        }
        // 01第一次 02非一次性
        EditAiPosterDetailPage.navigatorPush(context, url, itemBean, "", "03",
            currentPsd, "01", name: _name, address: _address, logo: _logo);
      },
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: AspectRatio(
          aspectRatio: 1,
          child: Container(
            color: Colors.black,
            child: Stack(
              alignment: Alignment.center,
              children: <Widget>[
                VgCacheNetWorkImage(itemBean?.effecturl?? "",imageQualityType: ImageQualityType.middleDown,),
              ],
            ),
          ),
        ),
      ),
    );
  }

  String getPsd(String psdJson){
    if(psdJson.contains("\\r")){
      psdJson = psdJson.replaceAll("\\r", "<br/>");
    }
    if(psdJson.contains("\\n")){
      psdJson = psdJson.replaceAll("\\n", "<br/>");
    }
    String js = "get_data('${psdJson}')";
    print("js:" + js);
    return js;
  }


  String getUrl() {
    String posterUrl = "https://etpic.we17.com/template/html/diyPoster_detail.html";
    CompanyInfoBean companyInfoBean =  UserRepository.getInstance().userData.companyInfo;
    ComLogoBean logoBean = UserRepository.getInstance().userData.comLogo;
    String name = companyInfoBean?.companynick??"";
    String address = companyInfoBean?.address??"";
    String logo = "";
    bool transFlag = false;
    if(logoBean != null){
      if(StringUtils.isNotEmpty(logoBean.squareTransparentLogo) && "-1" != logoBean.squareTransparentLogo){
        logo = logoBean.squareTransparentLogo;
        transFlag = true;
      }else if(StringUtils.isNotEmpty(logoBean.squareOpaqueLogo) && "-1" != logoBean.squareOpaqueLogo){
        logo = logoBean.squareOpaqueLogo;
      }else{
        if (!StringUtils.isEmpty(
            companyInfoBean?.companylogo ?? "") && ((companyInfoBean?.companylogo ?? "").contains("http://etpic.we17.com") || (companyInfoBean?.companylogo ?? "").contains("https://etpic.we17.com"))) {
          logo = companyInfoBean?.companylogo ?? "";
        }
      }
    }else{
      if (!StringUtils.isEmpty(
          companyInfoBean?.companylogo ?? "") && ((companyInfoBean?.companylogo ?? "").contains("http://etpic.we17.com") || (companyInfoBean?.companylogo ?? "").contains("https://etpic.we17.com"))) {
        logo = companyInfoBean?.companylogo ?? "";
      }
    }

    String url;
    if (StringUtils.isNotEmpty(logo)) {
      url =
      "$posterUrl?name=${Uri.encodeComponent(name)}&address=${Uri.encodeComponent(address)}&logo=${Uri.encodeComponent(logo)}";
    } else {
      url =
      "$posterUrl?name=${Uri.encodeComponent(name)}&address=${Uri.encodeComponent(address)}";
    }
    _name = name;
    _address = address;
    _logo = logo;
    //01 浏览模式    02编辑
    url = url + "&type=02";
    url = url + "&t=" + DateTime.now().millisecondsSinceEpoch.toString();
    print("生成的url");
    print(url);
    return url;
  }


  @override
  bool get wantKeepAlive => true;
}
